package luj.groovy.excel.internal.table.header

import groovy.transform.PackageScope
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.util.CellRangeAddress

@PackageScope
class FieldPosMap {

  interface Item {

    FieldImpl field()
  }

  FieldPosMap(List<CellRangeAddress> mergedList) {
    _mergedList = mergedList
  }

  void add(Cell cell, FieldImpl field) {
    String key = makeKey(cell.rowIndex, cell.columnIndex)

    _posMap[key] = new Item() {
      @Override
      FieldImpl field() {
        return field
      }
    }
  }

  Item get(int row, int col) {
    String key = makeKey(row, col)
    Item result = _posMap[key]
    if (result) {
      return result
    }

    String key2 = _mergedList.stream()
        .filter { it.isInRange(row, col) }
        .findAny()
        .map { makeKey(it.firstRow, it.firstColumn) }
        .orElseThrow { throw new IllegalStateException("找不到字段，位置：${it}") }

    return _posMap[key2]
  }

  private String makeKey(int row, int col) {
    return row + '_' + col
  }

  private final Map<String, Item> _posMap = [:]

  private final List<CellRangeAddress> _mergedList
}
